package com.example.esp8266.activity.utile;

import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author lgd
 * @Date 2023/3/23 15:20
 */
public class SpannableUtil {
    /**
     * 关键字高亮变色
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字
     * @return
     */
    public static SpannableStringBuilder findSearch(int color, String text, String keyword) {
//        SpannableString s = new SpannableString(text);
        SpannableStringBuilder s = new SpannableStringBuilder(text);
        Pattern pattern = Pattern.compile(keyword);
        Matcher matcher = pattern.matcher(s);

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //设置字体改变颜色
//            s.setSpan(new BackgroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 为文本设置背景颜色
        }

//        return SpannableString.valueOf(s);
        return SpannableStringBuilder.valueOf(s);
    }

    /**
     * 多个关键字高亮变色
     * @param color   变化的色值
     * @param text    文字
     * @param keyword 文字中的关键字数组
     * @return
     */
    public static SpannableString findSearch(int color, String text, String...keyword) {
        SpannableString s = new SpannableString(text);
        for (int i = 0; i < keyword.length; i++) {
            Pattern p = Pattern.compile(keyword[i]);
            Matcher m = p.matcher(s);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return s;
    }
}
